package cn.shengchao.job;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.shengchao.examstar.rpc.wecom.api.LocalToWeComRequestApi;
import cn.shengchao.qywx.infrastrure.po.QywxCustomer;
import cn.shengchao.qywx.infrastrure.po.QywxUser;
import cn.shengchao.qywx.infrastrure.po.QywxUserQrcode;
import cn.shengchao.qywx.infrastrure.service.QywxCustomerService;
import cn.shengchao.qywx.infrastrure.service.QywxUserQrcodeService;
import cn.shengchao.qywx.infrastrure.service.QywxUserService;
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.aizuda.snailjob.common.log.SnailJobLog;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: examstarapi
 * @description: 企业微信数据加载
 * @author: Xiong weiqiang
 * @create: 2025-04-18 14:34
 */
@Component
@RequiredArgsConstructor
public class WeComUserSyncJob {
    @Autowired
    private QywxUserService qywxUserService;
    @Autowired
    private QywxCustomerService qywxCustomerService;
    @Autowired
    private QywxUserQrcodeService qywxUserQrcodeService;
    @DubboReference
    LocalToWeComRequestApi localToWeComRequestApi;

    @JobExecutor(name = "WecomSyncDepartUserQrcodeJob")
    public ExecuteResult syncDepartUserQrcodeJob(JobArgs jobArgs) {
        long startTime = System.currentTimeMillis();
        SnailJobLog.REMOTE.info("开始执行同步企微通讯录成员二维码到本地任务" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        List<QywxUserQrcode> qywxUserQrcodes=qywxUserQrcodeService.list(Wrappers.lambdaQuery(QywxUserQrcode.class));
        Map<String,List<QywxUserQrcode>> qywxUserQrcodeMap=qywxUserQrcodes.stream()
                .collect(Collectors.groupingBy(QywxUserQrcode::getUser));
        List<QywxUser> qywxUsers=qywxUserService.list(Wrappers.lambdaQuery(QywxUser.class).eq(QywxUser::getStatus,1)
                .and(
                        a->a.eq(QywxUser::getQrCodeStatus,0).or().isNull(QywxUser::getQrCodeStatus)
                )
        );
        if (CollUtil.isNotEmpty(qywxUsers)){
            for (QywxUser qywxUser : qywxUsers){
                List<QywxUserQrcode> qywxUserQrcodes1 = qywxUserQrcodeMap.get(qywxUser.getUserId());
                if (CollUtil.isNotEmpty(qywxUserQrcodes1)){
                    QywxUserQrcode qywxUserQrcode = qywxUserQrcodes1.getFirst();
                    qywxUser.setQrCodeStatus(1);
                    qywxUser.setQrCodeUrl(qywxUserQrcode.getQrCode());
                    qywxUserService.updateById(qywxUser);
                }
            }
            List<QywxUser> notQrCodeUsers=qywxUserService.list(Wrappers.lambdaQuery(QywxUser.class).eq(QywxUser::getStatus,1).and(
                    a->a.eq(QywxUser::getQrCodeStatus,0).or().isNull(QywxUser::getQrCodeStatus)
            ).orderByAsc(QywxUser::getLastUpdateTime).last("limit 10"));
            if (CollUtil.isNotEmpty(notQrCodeUsers)){
                List<String> userIds=notQrCodeUsers.stream().map(QywxUser::getUserId).toList();
                localToWeComRequestApi.checkNotQrCodes(userIds);
            }
        }
        long endTime = System.currentTimeMillis();
        SnailJobLog.REMOTE.info("结束执行同步企微通讯录成员二维码到本地任务：，耗时："+(endTime-startTime)+"毫秒");
        return ExecuteResult.success();
    }
    /** 
     * method : syncDepartUserToLocal
     * description :     同步企业微信通讯录成员(用户初始化，只调用一次，其他靠企微的消息事件同步）
     * @param jobArgs \{@link JobArgs \} 
     * @return : com.aizuda.snailjob.client.model.ExecuteResult
     * @author : Xiong weiqiang 
     * @CreateDate : 2025-04-18 16:06:12
     *  
     * @Reviewed : 
     * @UpdateLog :    Name    Date    Reason/Contents
     *             ---------------------------------------
     *                ****    ****    **** 
     *
     */
    @JobExecutor(name = "WecomSyncDepartUserToLocalJob")
    public ExecuteResult syncDepartUserToLocal(JobArgs jobArgs) {
        long startTime = System.currentTimeMillis();
        SnailJobLog.REMOTE.info("开始执行同步企微通讯录成员到本地任务" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        localToWeComRequestApi.syncAllCpUser();
        long endTime = System.currentTimeMillis();
        SnailJobLog.REMOTE.info("结束执行同步企微通讯录成员到本地任务：，耗时："+(endTime-startTime)+"毫秒");
        return ExecuteResult.success();
    }
    /**
     * method : syncDepartUserDetailToLocal
     * description :     同步企业微信的成员信息和客户信息(用户初始化，只调用一次，其他靠企微的消息事件同步）
     * @param jobArgs \{@link JobArgs \}
     * @return : com.aizuda.snailjob.client.model.ExecuteResult
     * @author : Xiong weiqiang
     * @CreateDate : 2025-04-18 16:03:55
     *
     * @Reviewed :
     * @UpdateLog :    Name    Date    Reason/Contents
     *             ---------------------------------------
     *                ****    ****    ****
     *
     */
    @JobExecutor(name = "WecomSyncDepartUserDetailToLocalJob")
    public ExecuteResult syncDepartUserDetailToLocal(JobArgs jobArgs) {
        long startTime = System.currentTimeMillis();
        SnailJobLog.REMOTE.info("开始执行同步企微成员详情和客户到本地任务" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        List<QywxUser> qywxUsers=qywxUserService.list(Wrappers.lambdaQuery(QywxUser.class).eq(QywxUser::getLoadStatus,0));
        if (CollUtil.isNotEmpty(qywxUsers)){
            List<String> userIds = qywxUsers.stream().map(QywxUser::getUserId).toList();
            System.out.println("找到企业微信的成员数："+userIds.size());
            for (String userId : userIds){
                localToWeComRequestApi.syncCpUserInfo(userId);
                localToWeComRequestApi.fetchCpUserCustomers(userId);
            }
        }
        long endTime = System.currentTimeMillis();
        SnailJobLog.REMOTE.info("结束执行同步企微成员详情和客户到本地任务：，耗时："+(endTime-startTime)+"毫秒");
        return ExecuteResult.success();
    }
    /**
     * method : syncContactUserToLocal
     * description :     客户详情
     * {
     *     "externalContact": {
     *         "externalUserId": "wmEeoOZwAAeRx4aE6uJGJRRKFCQTfmBg",
     *         "name": "黎度",
     *         "avatar": "http://wx.qlogo.cn/mmhead/KCAvfDRSPlxjU4HtT34kmtGvhL4F0NVjJUibHibjvVrDnvJ51uNNSgcsfib2ibh1ibjCQMnwnOq0B8dg/0",
     *         "type": 1,
     *         "gender": 1,
     *         "unionId": "oCeV21DUzEUPxfVesXzp2mlSnI6U"
     *     },
     *     "followedUsers": [
     *         {
     *             "userId": "Xiongweiqiang",
     *             "remark": "高启强",
     *             "description": "",
     *             "createTime": 1744340976,
     *             "remarkMobiles": [ ],
     *             "tags": [
     *                 {
     *                     "groupName": "学员等级",
     *                     "tagName": "核心",
     *                     "tagId": "etEeoOZwAA_2QQgGB6hJGESLgFTgjO-w",
     *                     "type": 1
     *                 }
     *             ],
     *             "remarkCorpName": "星光",
     *             "addWay": "1",
     *             "operatorUserId": "wmEeoOZwAAeRx4aE6uJGJRRKFCQTfmBg"
     *         }
     *     ]
     * }
     * @param jobArgs \{@link JobArgs \}
     * @return : com.aizuda.snailjob.client.model.ExecuteResult
     * @author : Xiong weiqiang
     * @CreateDate : 2025-04-18 17:10:50
     *
     * @Reviewed :
     * @UpdateLog :    Name    Date    Reason/Contents
     *             ---------------------------------------
     *                ****    ****    ****
     *
     */
    @SaIgnore
    @JobExecutor(name = "WecomSyncContactUserToLocalJob")
    public ExecuteResult syncContactUserToLocal(JobArgs jobArgs) {
        long startTime = System.currentTimeMillis();
        SnailJobLog.REMOTE.info("开始执行同步企微客户的UnionId到本地任务" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        List<QywxCustomer> qywxCustomers=qywxCustomerService.list(Wrappers.lambdaQuery(QywxCustomer.class).eq(QywxCustomer::getLoadStatus,0));
        if (CollUtil.isNotEmpty(qywxCustomers)){
            List<String> customerIds= qywxCustomers.stream().map(QywxCustomer::getExternalUserId).toList();
            System.out.println("找到企业微信的客户数："+customerIds.size());
            for (String userId : customerIds){
                localToWeComRequestApi.updateExternalUserCustomerDetail(userId,null);
            }
        }
        long endTime = System.currentTimeMillis();
        SnailJobLog.REMOTE.info("开始执行同步企微客户的UnionId到本地任务：，耗时："+(endTime-startTime)+"毫秒");
        return ExecuteResult.success();
    }
}